//
//  OAuthViewController.swift
//  XDweibo
//
//  Created by HanXingda on 15/6/25.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController,UIWebViewDelegate {
    private let WB_Client_ID = "2130193683"
    private let WB_Redirect_URI = "http://baidu.com"
    private let App_Secret = "93e2a0e893398f2305541603c50f18a2"
    lazy var webview : UIWebView = {
    let webview = UIWebView()
        webview.delegate = self
        return webview
    }()
    override func loadView() {
        super.loadView()
                view = webview
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "新浪微博"
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        let url = NSURL(string: urlString)
        webview.loadRequest(NSURLRequest(URL: url!))
        
    }

    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
       
        //判断，如果不是回调地址就继续加载请求
        if !urlString.hasPrefix(WB_Redirect_URI){
            
            return true
        }
        
        //如果是回调地址，判断是否有授权码，如果有记录，没有关闭界面
        let query = request.URL!.query!
        let codeStr = "code="
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("获取授权码\(code)")
            loadAccessToken(code)
        } else{
            print("取消授权")
            close()
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载中")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func loadAccessToken(code : String) {
       

        let urlString = "oauth2/access_token"
        
        let parameter = ["client_id" :WB_Client_ID,
            "client_secret" : App_Secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : WB_Redirect_URI]
        NetWorkTools.sharedNetworkTools().POST(urlString, parameters: parameter, success: { (_, json) -> Void in
             UserAccount(dict: json as! [String : AnyObject]).loadUserInfo { (account, error) -> () in
                if account != nil {
                    print(account)
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
            }
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
}
